package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    DishMapper dishMapper;
    @Autowired
    DishFlavorMapper dishFlavorMapper;
    @Autowired
    SetmealDishMapper setmealDishMapper;
    @Autowired
    SetmealMapper setmealMapper;
    /**
    * @Description: 新增菜品
    * @Author: 锦章
    * @Date: 2024/3/5
    */
    //由于我们新增菜品需要向菜品表和口味表两个表中添加数据，所以需要用到事务。
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        //将DishDTO对象中的属性拷贝到dish对象
        BeanUtils.copyProperties(dishDTO,dish);
        //向菜单表dish插入一条数据
        dishMapper.insert(dish);
        //获取菜单表中主键的值，set到口味表的外键上。
        Long dishId = dish.getId();
        //获取前端传过来的口味集合，并将id一一插入到各个集合中
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null &&flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //批量插入
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * @Description: 分页查询菜品信息
     * @Author: 锦章
     * @Date: 2024/3/6
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //调用pageHerpler进行分页
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page =  dishMapper.pageQuery(dishPageQueryDTO);
        long total = page.getTotal();
        List<DishVO> result = page.getResult();
        return new PageResult(total,result);
    }
    /**
     * @Description: 批量删除菜品
     * @Author: 锦章
     * @Date: 2024/3/6
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断菜品是否可以被删除----查询菜品是否是起售中
        ids.forEach(id->{
         Dish dish = dishMapper.getById(id);
         //判断菜品状态是否为起售
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //判断菜品是否可以被删除----查询菜品是否被套餐关联
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealIds!=null && setmealIds.size() >0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //执行批量删除操作
        ids.forEach(id->{
            //批量删除菜品
            dishMapper.deleteById(id);
            //批量删除与菜品关联的口味数据
            dishFlavorMapper.deleteByDishId(id);
        });

    }

    /**
     * @Description: 根据id查询菜品和相关联的口味数据
     * @Author: 锦章
     * @Date: 2024/3/6
     */
    public DishVO getById(Long id) {
        //根据id查新菜品相关的数据
        Dish dish = dishMapper.getById(id);
        //根据id查询口味相关的数据
        List<DishFlavor> dishFlavors =  dishFlavorMapper.getById(id);
        //将查询出来的菜品和口味数据封装到DishVO对象中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }
    /**
     * @Description: 修改菜品
     * @Author: 锦章
     * @Date: 2024/3/6
     */
    public void updateWithFlavor(DishDTO dishDTO) {
        //根据传过来的参数，修改菜品表对应的属性
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        //修改口味表
        //先删除原来的口味表的数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //在插入更新的口味表数据
        //从前端穿过来的DTO对象中，获取修改的口味数据，数据可能是多条、可能没有数据
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if(dishFlavors!=null && dishFlavors.size()>0){
            dishFlavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(dishFlavors);
        }
    }

    /**
     * @Description: 菜品起售禁售
     * @Author: 锦章
     * @Date: 2024/3/6
     */
    @Transactional
        public void startOrStop(Integer status,Long id) {
            Dish dish = Dish.builder()
                    .id(id)
                    .status(status)
                    .build();
            dishMapper.update(dish);
            if (status == StatusConstant.DISABLE) {
                // 如果是停售操作，还需要将包含当前菜品的套餐也停售
                List<Long> dishIds = new ArrayList<>();
                dishIds.add(id);
                // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
                List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
                if (setmealIds != null && setmealIds.size() > 0) {
                    for (Long setmealId : setmealIds) {
                        Setmeal setmeal = Setmeal.builder()
                                .id(setmealId)
                                .status(StatusConstant.DISABLE)
                                .build();
                        setmealMapper.update(setmeal);
                    }
                }
            }
        }

    /**
     * @Description: 根据分类id查询菜品
     * @Author: 锦章
     * @Date: 2024/3/7
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getById(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
